<template>
  <el-dialog :visible="showDialog" @close="closeFn">
    <!-- 表单 -->
    <el-form ref="form" :model="formData" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="confirmFn">确定</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { addRole, getRoleDetail, EditRole } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名称长度1到10', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名称长度1到20', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeFn() {
      this.formData = {
        title: '',
        description: ''
      }
      this.$emit('update:showDialog', false)
      // 重置表单
      this.$refs.form.resetFields()
    },
    // 确定事件
    async confirmFn() {
      try {
        // 验证
        await this.$refs.form.validate()
        // console.log(this.formData)
        if (this.formData.id) {
          //  编辑
          await EditRole(this.formData)
          this.$message.success('编辑角色成功')
        } else {
          //  新增
          await addRole(this.formData)
          this.$message.success('新增角色成功')
        }
        // 关闭弹窗
        this.$emit('update:showDialog', false)
        // 刷新
        this.$emit('updateEvent')
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id获取角色详情并回显
    async getRoleById(id) {
      const res = await getRoleDetail(id)
      this.formData = res.data
      console.log(this.formData)
    }
  }
}
</script>

<style>
</style>
